package main

import (
	"../fileutil"
	"../picutil"
	"bufio"
	"fmt"
	_ "image/jpeg"
	_ "image/png"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

func main() {

	scanner := bufio.NewReader(os.Stdin)

	picturePath, _ := fileutil.GetInputLine(scanner, "请输入壁纸目录：")
	compressPath, _ := fileutil.GetInputLine(scanner, "请输入压缩目录：")
	outPath, _ := fileutil.GetInputLine(scanner, "请输入输出目录：")

	CleanPicture2(picturePath, compressPath, outPath)

}

func CleanPicture2(picturePath, compressPath, outPath string) {
	// 创建输出目录
	picOutPath, _ := fileutil.MkDir(outPath, "带添加壁纸")
	compressOutPath, _ := fileutil.MkDir(outPath, "待删除压缩")
	pic1920OutPath, _ := fileutil.MkDir(picOutPath, "1920")
	pic1080OutPath, _ := fileutil.MkDir(picOutPath, "1080")

	pictureMap := make(map[string]os.FileInfo)
	compressSet := make(map[string]bool)

	// 待删除切片
	compressDeleteList := make([]string, 0)
	// 待复制壁纸
	picture1920CopyList := make([]string, 0)
	picture1080CopyList := make([]string, 0)

	fmt.Println("Start . . . ")

	// 处理壁纸
	pictures, _ := ioutil.ReadDir(picturePath)
	for _, picture := range pictures {
		fileName := picture.Name()

		// 移除系统文件
		if fileutil.DealDesktop(picturePath, fileName) {
			continue
		}

		// 按照 “-” 分割文件名，并去除处理符号集（rotate、tailor、combine等括号内的全部内容）
		a := strings.LastIndexByte(fileName, '.')
		name := fileName[0:a]

		// 移除 【4K】
		if name[len(name)-8:] == "【4K】" {
			name = name[0 : len(name)-8]
		} else {
			fmt.Println(name + " 后4位为： " + name[len(name)-8:])
			panic("壁纸文件 " + fileName + " 缺少‘【4K】’后缀")
		}

		// 将壁纸信息存入map
		if _, ok := pictureMap[name]; ok == true {
			panic("壁纸 " + fileName + " 已存在！")
		}
		pictureMap[name] = picture

	}

	// 清除压缩壁纸
	compressPictures, _ := ioutil.ReadDir(compressPath)
	for _, picture := range compressPictures {
		fileName := picture.Name()
		if fileutil.DealDesktop(compressPath, fileName) {
			continue
		}

		a := strings.LastIndexByte(fileName, '.')
		name := fileName[0:a]
		if _, ok := pictureMap[name]; ok {
			compressSet[name] = true
			delete(pictureMap, name)
		} else {
			// 如果压缩壁纸没有对应的壁纸，则删除
			compressDeleteList = append(compressDeleteList, fileName)
		}
	}

	// 复制待添加的壁纸
	for name, picture := range pictureMap {
		if _, ok := compressSet[name]; !ok {
			fileName := picture.Name()
			// 读取图片尺寸
			config := picutil.Config(filepath.Join(picturePath, fileName))
			g := float32(config.Height) / float32(config.Width)
			if g > 0.5625 {
				picture1920CopyList = append(picture1920CopyList, fileName)
			} else {
				picture1920CopyList = append(picture1080CopyList, fileName)
			}
		}
	}

	// 统一删除和复制操作
	fileutil.MoveFiles(compressDeleteList, compressPath, compressOutPath)
	fmt.Println()

	fileutil.CopyFiles(picture1920CopyList, picturePath, pic1920OutPath)
	fmt.Println()

	fileutil.CopyFiles(picture1080CopyList, picturePath, pic1080OutPath)
	fmt.Println()

	fmt.Println()
	fmt.Println("END!")
}
